 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Android
 * Package  : net.solosky.easyavatar.activity
 * File     : Welcome.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2011-11-11
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.activity;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.solosky.easyavatar.R;
import net.solosky.easyavatar.bean.Contact;
import net.solosky.easyavatar.bean.ProviderMeta;
import net.solosky.easyavatar.bean.ProviderMeta.AuthType;
import net.solosky.easyavatar.utils.AsyncTask;
import net.solosky.easyavatar.utils.AsyncTask.Status;
import net.solosky.easyavatar.utils.Constants;
import net.solosky.easyavatar.utils.ContactManager;
import net.solosky.easyavatar.utils.DbPersist;
import net.solosky.easyavatar.utils.FakeX509TrustManager;
import net.solosky.easyavatar.utils.Globals;
import net.solosky.easyavatar.utils.Utils;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.Photo;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.view.KeyEvent;

/**
 *
 * 欢迎屏幕，执行初始化
 *
 * @author solosky <solosky772@qq.com>
 *
 */
public class Welcome extends Activity {

	private InitializingTask mInitTask;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ui_welcome);
		
		mInitTask = new InitializingTask();
		mInitTask.execute((Void[])null);
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//对用户按返回键的处理
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(!mInitTask.isCancelled() &&
					mInitTask.getStatus()!=Status.FINISHED){
				mInitTask.cancel(true);
			}
		}
		return super.onKeyDown(keyCode, event);

	}



	private class InitializingTask extends AsyncTask<Void, Integer, Void>{
		@Override
		protected void onPostExecute(Void result) {
			String nextIntentName = getIntent().getStringExtra("welcome.nextIntent");
			if(nextIntentName!=null){
				try {
					Class<Activity> nextIntentClass = (Class<Activity>) Class.forName(nextIntentName);
					Intent intent = getIntent();
					intent.setClass(Welcome.this,nextIntentClass);
					startActivity(intent);
				} catch (ClassNotFoundException e) {
					startActivity(new Intent(Welcome.this, Main.class));
				}
			}else{
				startActivity(new Intent(Welcome.this, Main.class));
			}
			
			Welcome.this.finish();
		}

		@Override
		protected Void doInBackground(Void... params) {
			if(!Globals.IS_INITILIZED){
				try {
					long startTime = System.currentTimeMillis();
					//初始化数据库连接
					Globals.DB_PERSIST = new DbPersist(getApplicationContext());
					
					//初始化可用的好友提供接口信息
					Globals.PROVIDER_META_LIST = new ArrayList<ProviderMeta>();
					SAXBuilder builder = new SAXBuilder();
					Document doc = builder.build(getResources().openRawResource(R.raw.providers));
					List providers = doc.getRootElement().getChildren();
					Iterator<Element> it = providers.iterator();
					while(it.hasNext()){
						Element el = it.next();
						ProviderMeta meta = new ProviderMeta();
						
						meta.setCode(el.getChildText("code"));
						meta.setTitle(el.getChildText("title"));
						meta.setIntro(el.getChildText("intro"));
						meta.setAuthType("web".equals(el.getChildText("auth"))?AuthType.WEB:AuthType.OAUTH);
						meta.setIconLarge(el.getChildText("icon-large"));
						meta.setIconSmall(el.getChildText("icon-small"));
						meta.setClazz(el.getChildText("class"));
						meta.setAppKey(el.getChildText("appKey"));
						meta.setAppSecret(el.getChildText("appSecret"));
						meta.setExpired(Long.parseLong(el.getChildText("expired")));
						meta.setAuthInfo(Globals.DB_PERSIST.queryAuthInfo(meta.getCode()));
						
						Globals.PROVIDER_META_LIST.add(meta);
					}
					Utils.dout("loaded "+Globals.PROVIDER_META_LIST.size()+" provider metas.");
					
					//加载联系人
					Globals.CONTACT_MANAGER = new ContactManager();
					Globals.CONTACT_MANAGER.loadAllContacts(Welcome.this);
					Utils.dout("loaded "+Globals.CONTACT_MANAGER.getContactNum()+" contacts.");
					//TODO ..Check updates...
					
					FakeX509TrustManager.allowAllSSL();
					
					long endTime = System.currentTimeMillis();
					long delayTime = Constants.WELCOME_MIN_DISPLAY_TIME-(endTime-startTime);	//至少3秒,以免界面很快关闭
					if(delayTime>0){
						Thread.sleep(delayTime);
					}
					
					Globals.IS_INITILIZED = true;
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return null;
		}
		
	}
}
